const path = require("path")
/**
 * 用户功能模块：
 * 1.用户登录校验,登录成功，签发token
 * 
 * 实现用户注册业务逻辑：
 * 1.获取表单上用户的注册数据
 * 2.执行数据库的查询操作
 * 3.用户名已存在，则返回错误信息给客户端
 * 4.用户名不存在，执行数据库新增
 * 5.新增成功，注册成功
 * 6.新增失败，注册失败
 */
const db = require("../../dbutil/index");
const sql = require("../../dbutil/sql");
const token = require("../../util/token");

module.exports = {
   login: (req, res) => {
      //获取请求对象中的用户数据
      let { uname, upass } = req.body;
      // res.send('1')
      //调用db.query()
      db.query(sql.users.login, [uname, upass], (err, results) => {
         if (err) {
            //返回json对象：状态码、状态描述、数据
            res.send({ code: 505, msg: err.message });
         } else {
            //判断登录是否成功
            if (results.length > 0) {
               //用户认证成功，签发token,并将token写回客户端
               token.setToken(results[0].uname, results[0].uid).then((t) => {
                  return res.send({
                     code: 200,
                     msg: "登录成功",
                     data: {
                        token: t,
                        user: results
                     }
                  });
               });
            } else {
               res.send({
                  code: 201,
                  msg: "用户名或密码错误，登录失败",
                  data: {}
               });
            }
         }
      });
   },



   // 注册
   regist: (req, res) => {
      let { uname, upass } = req.body;
      console.log(uname, upass);
      db.query(sql.users.userByname, [uname], (err1, results1) => {
         if (err1) {
            res.send({ code: 505, msg: "数据库执行错误" });
         } else {
            if (results1.length > 0) {
               // 3.用户名已存在，则返回错误信息给客户端
               res.send({
                  code: 202,
                  msg: "用户名已存在,注册失败",
               });
            } else {
               db.query(sql.users.addUser, [uname, upass, Date.now()], (err2, results2) => {
                  if (err2) {
                     console.log(err2);
                     res.send({ code: 505, msg: "数据库执行错误" });
                  } else {
                     if (results2.affectedRows > 0) {
                        res.send({ code: 200, msg: "注册成功" });
                     } else {
                        res.send({ code: 201, msg: "注册失败" });
                     }
                  }
               })
            }
         }
      })
   },


   // 修改密码
   updateUpass: (req, res) => {
      let { uname, oldpass, newpass } = req.body;
      db.query(sql.users.login, [uname, oldpass], (err1, results1) => {
         if (err1) res.send({ code: "505", msg: "数据库执行错误" });
         else {
            if (results1.length) {
               db.query(sql.users.updateUpass, [newpass, uname], (err2, results2) => {
                  if (err2) {
                     res.send({ code: 505, msg: "数据库执行错误" })
                  } else {
                     if (results2.affectedRows > 0) {
                        res.send({ code: 200, msg: "修改成功" });
                     } else {
                        res.send({ code: 201, msg: "修改失败" });
                     }
                  }
               })
            } else {
               res.send({ code: "400", msg: "原密码错误" });
            }
         }

      })
   },



   // 上传头像
   uploadAvator: (req, res) => {
      // console.log(req.body, req.file);
      let { uid } = req.body;
      let { filename } = req.file;
      // 可以默认一个头像,如果没有点击修改头像就可以默认一张图片给他传上去
      const Avatar_img = `http://127.0.0.1:3000/images/${filename}`
      // const Avatar_img = req.file.destination + '/' + req.file.filename;
      db.query(sql.users.uploadAvatar, [Avatar_img, uid], (err, results) => {
         console.log(err);
         if (err) {
            res.send({ code: 505, msg: "数据库执行失败" });
         } else {
            // console.log(results[0].avatar_img);
            if (results.affectedRows === 0) {
               res.send({ code: 400, msg: "没找到该用户" });
            } else {
               res.send({ code: 200, msg: "上传成功", data: Avatar_img });
            }
         }
      })
   },


   // 获取个人信息
   getUserImg: (req, res) => {
   let {uid}=req.query;
   db.query(sql.users.getUserImg,[uid],(err,results)=>{
      if(err){
         res.send({code:505,msg:"数据库执行失败"})
      }else{
        if(results.length>0){
         res.send({code:200,msg:"获取成功",data:results})
        }else{
         res.send({code:201,msg:"获取失败"});
        }
      }
   })
   },

   // 收藏新闻
   collectNews: (req, res) => {
      let { news_id, uid } = req.body;
      db.query(sql.users.checkCollection, [news_id, uid], (err1, results1) => {
         console.log(err1);
         if (err1) {
            console.log(err1);
            res.send({ code: 505, msg: "数据库执行错误" });
         } else {
            if (results1.length > 0) {
               res.send({ code: 400, msg: "已收藏" })
            } else {
               db.query(sql.users.addCollection, [news_id, uid, Date.now()], (err2, results2) => {
                  console.log(err2);
                  if (err2) {
                     console.log(err2);
                     res.send({ code: 505, msg: "数据库执行错误" });
                  } else {
                     res.send({ code: 200, msg: "新闻收藏成功" });
                  }
               })
            }
         }
      })
   },


   //判断是否收藏是true,false
   isCollect: (req, res) => {
      let { news_id, uid } = req.query;
      db.query(sql.users.checkCollection, [news_id, uid], (err, results) => {
         if (results.length > 0) {
            res.send({ code: 200, msg: "有数据", data: true })
         } else {
            res.send({ code: 201, msg: "无数据", data: false });
         }
      })
   },


   // 取消收藏
   cancelCollection: (req, res) => {
      let { news_id, uid } = req.body;
      db.query(sql.users.cancelCollection, [news_id, uid], (err, results) => {
         if (err) {
            res.send({ code: 505, msg: "数据库执行错误" })
         } else {
            // 等于没有执行这个语句，就没有查询到这个数据
            if (results.affectedRows === 0) {
               res.send({ code: 400, msg: "没有收藏这条新闻" })
            } else {
               res.send({ code: 200, msg: "取消收藏成功" })
            }
         }
      })
   },


   // 获取用户收藏新闻
   getNewsCollect: (req, res) => {
      let { uid } = req.query;
      db.query(sql.users.getNewsCollect, [uid], (err, results) => {
         if (err) {
            res.send({ code: 505, msg: "数据库执行错误" });
         } else {
            res.send({ code: 200, msg: "查询成功", data: results })
         }
      })
   },


   // 获取用户收藏新闻的总量
   uNewsCollectTotal: (req, res) => {
      let { uid } = req.query;
      db.query(sql.users.uCollectTotal, [uid], (err, results) => {
         if (err) {
            res.send({ code: 505, msg: "数据库执行错误" })
         } else {
            res.send({ code: 200, msg: "获取成功", data: results[0] });
            // res.json({ count: results[0].news_total });  
         }
      })
   },



   // 添加用户浏览新闻历史记录
   // addNewsHistory: (req, res) => {
   //    let { uid, news_id } = req.body;
   //    db.query(sql.users.addNewsHistory, [uid, news_id, Date.now()], (err, results) => {
   //       if (err) {
   //          console.log(err);
   //          res.send({ code: 505, msg: "数据库执行错误" });
   //       } else {
   //          if (results.affectedRows > 0) {
   //             res.send({ code: 200, msg: "数据新增成功", data: { results } })
   //          }
   //       }
   //    })
   // },


   // 获取用户新闻浏览历史
   getNewsHistory: (req, res) => {
      let { uid } = req.query;
      db.query(sql.users.getNewsHistory, [uid], (err, results) => {
         if (err) res.send({ code: 505, msg: "数据库执行错误" });
         else res.send({ code: 200, msg: "查询成功", data: results })
      })
   },


   // 用户点赞新闻
   thumbsUp: (req, res) => {
      let { news_id, uid } = req.body;
      db.query(sql.users.checkThumbsUp, [news_id, uid], (err1, results1) => {
         if (err1) {
            res.send({ code: 505, msg: "数据库执行错误" });
         } else {
            if (results1.length > 0) {
               // 用户已经点赞过，可以选择取消点赞或返回已点赞的信息
               res.send({ code: 400, msg: "你已经点赞了该条新闻" });
            } else {
               // 用户没有点赞过，插入新的点赞记录
               db.query(sql.users.addThumbsUp, [news_id, uid], (err2, results2) => {
                  if (err2) res.send({ code: 505, msg: "数据库执行错误" })
                  else res.send({ code: 200, msg: "点赞成功", data: { results2 } })
               })
            }
         }
      })
   },


   // 判断是否点赞返回true,false
   isThumbsUp: (req, res) => {
      let { news_id, uid } = req.query;
      db.query(sql.users.checkThumbsUp, [news_id, uid], (err, results) => {
         if (results.length > 0) {
            res.send({ code: 200, msg: "有数据", data: true })
         } else {
            res.send({ code: 201, msg: "无数据", data: false })
         }
      })
   },

   // 取消点赞新闻
   cancelThumbsUp: (req, res) => {
      let { news_id, uid } = req.body;
      console.log(news_id, uid);
      db.query(sql.users.cancelThumbsUp, [news_id, uid], (err, results) => {
         if (err) {
            res.send({ code: 505, msg: "数据库执行错误", err })
         } else {
            if (results.affectedRows === 0) {
               res.send({ code: 400, msg: "没有点赞这条新闻" });
            }
            else {
               res.send({ code: 200, msg: "取消点赞成功" });
            }
         }
      })
   },


   // 用户点赞评论
   CommThumbsUp: (req, res) => {
      let { comments_id, uid } = req.body;
      db.query(sql.users.checkeCommThumsbUp, [comments_id, uid], (err1, results1) => {
         if (err1) {
            res.send({ code: 505, msg: "数据库执行错误" });
         } else {
            if (results1.length > 0) {
               res.send({ code: 400, msg: "你已经点赞了该条评论" });
            } else {
               db.query(sql.users.addCommThumbsUp, [uid, comments_id], (err2, results2) => {
                  if (err2) res.send({ code: 505, msg: "数据库执行错误" })
                  else res.send({ code: 200, msg: "点赞评论成功", data: results2 })
               })
            }
         }
      })
   },


   // 取消点赞评论
   cancelCommThumbsUp: (req, res) => {
      let { comments_id, uid } = req.body;
      db.query(sql.users.cancelCommThumbsUp, [comments_id, uid], (err, results) => {
         if (err) {
            res.send({ code: 505, msg: "数据库执行错误" })
         } else {
            // 如果没有记录被删除，说明用户之前没有点赞  
            if (results.affectedRows === 0) {
               res.send({ code: 400, msg: "没有点赞这条评论" })
            } else {
               res.send({ code: 200, msg: "取消点赞成功" });
            }
         }
      })
   },

}
